/*
 * @Author: zi.yang
 * @Date: 2022-02-08 19:52:28
 * @LastEditors: zi.yang
 * @LastEditTime: 2022-02-09 18:05:25
 * @Description: In User Settings Edit
 * @FilePath: \api-generator\app\service\api-doc.js
 */
'use strict';
const Service = require('egg').Service;
const AjaxResponse = require('../utils/AjaxResponse');

class ApiDocService extends Service {
  async apiDocList() {
    const { ctx } = this;
    try {
      const create_by = ctx.user._id;
      const data = await ctx.model.ApiDoc.find({ create_by });
      return AjaxResponse.success({ success: '查询成功', data });
    } catch (error) {
      return AjaxResponse.error({ error });
    }
  }

  async addApiDocInfo(result) {
    const { ctx } = this;
    try {
      const { paths, info, host } = result.data;
      const pathStrArr = Object.keys(paths);
      const apiInfo = [];

      pathStrArr.forEach(path => {
        const methodObj = paths[path];
        Object.keys(methodObj).forEach(method => {
          const { operationId, parameters, summary, description, tags } = methodObj[method];
          apiInfo.push({ path, method, operationId, parameters, summary, description, tags });
        });
      });

      const userId = ctx.user._id;
      const { title: docName, description, version } = info;
      const docInfo = { docName, description, version, host, apiDoc: apiInfo, create_by: userId, update_by: userId };
      await ctx.model.ApiDoc.create(docInfo);
      return AjaxResponse.success({ msg: '文档存储成功！', data: docInfo });
    } catch (error) {
      return AjaxResponse.error({ msg: '文档存储失败！', error });
    }
  }
}

module.exports = ApiDocService;
